package models.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import models.Usuario;

public class DAOUsuario implements DAO<Usuario>{

	//Inserir Usuario
	@Override
	public void inserir(Usuario u) {
		try{
			String inserir = "insert into Usuario(email, senha, nome, dataNascimento, perfil) values(?, ?, ?, ?, ?)";
			PreparedStatement statement = DAOConexao.getConnection().prepareStatement(inserir);
			
			statement.setString(1, u.email);
			statement.setString(2, u.senha);
			statement.setString(3, u.nome);
			statement.setString(4, u.dataNascimento);
			statement.setString(5, u.perfil);
			
			statement.executeUpdate();
			
		}catch(SQLException e){
			e.printStackTrace();
			
		}finally{
			DAOConexao.closeConnection();
		}
		
	}

	//Atualizar o Usuario
	@Override
	public void atualizar(Usuario u) {
		
		try{
			String atualizar = "update Usuario set senha = ?, nome = ?, dataNascimento = ?, perfil = ? where email = ?";
			PreparedStatement statement = DAOConexao.getConnection().prepareStatement(atualizar);
			
			statement.setString(1, u.senha);
			statement.setString(2, u.nome);
			statement.setString(3, u.dataNascimento);
			statement.setString(4, u.perfil);
			statement.setString(5, u.email);
			
			statement.executeUpdate();
			
		}catch(SQLException e){
			e.printStackTrace();
			
		}finally{
			DAOConexao.closeConnection();
		}

	}

	//Deletar o usuario
	@Override
	public void deletar(Usuario u) {
		try{
			String deletar = "delete from Usuario where email = ?";
			PreparedStatement statement = DAOConexao.getConnection().prepareStatement(deletar);
			
			statement.setString(1, u.email);
			
			statement.executeUpdate();
			 
		}catch(SQLException e){
			e.printStackTrace();
			
		}finally{
			DAOConexao.closeConnection();
			
		}
		
	}

	//Listar
	@Override
	public List<Usuario> listar() {
		List<Usuario> usu = new ArrayList<Usuario>();
		
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");		
		
		try{
			String listar = "select * from Usuario";
			PreparedStatement statement = DAOConexao.getConnection().prepareStatement(listar);
			ResultSet result = statement.executeQuery();
			
			
			while(result.next()){
				Usuario u = new Usuario();
				
				u.email = result.getString(1);
				u.senha = result.getString(2);
				u.nome = result.getString(3);
				u.dataNascimento = df.format(result.getDate(4));
				u.perfil = result.getString(5);
				
				usu.add(u);
			}
			
			
		} catch(SQLException e){
			e.printStackTrace();
			
		}finally{
			DAOConexao.closeConnection();
		}
		
		return usu;
	}
	
}

